package com.itheima.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.common.TokenHolder;
import com.itheima.constant.TokenConstant;
import com.itheima.dao.EmployeeDao;
import com.itheima.domain.Employee;
import com.itheima.exception.NoDataException;
import com.itheima.service.impl.service.EmployeeServiceImpl;
import com.itheima.vo.EmployeeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequestMapping("/employee")
@RestController
public class EmployeeController  {
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private EmployeeServiceImpl employeeService;

    /**
     * 员工登录
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login (@RequestBody Employee employee){

        log.info(employee+"");
        //1.获取页面提交的password
        String password = employee.getPassword();
//      password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.根据页面提交的用户名username 查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());

        Employee emp = employeeService.getOne(queryWrapper);

        //3. 对比用户名，如果没有查到则返回登录失败结果
        if(emp==null){
            return  R.error("登录失败");
        }
        //4. 密码比对，如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            log.info("password"+password);
            log.info("emp.password"+emp.getPassword());
            return  R.error("登录失败");
        }
        //5. 查看员工状态 ，如果为已禁用状态，则返回员工已禁用结果
        if(emp.getStatus()==0){
            return  R.error("403,账号已禁用");
        }
        //生成token token当前用户的身份凭证 后续前端每次请求的时候都需要带上凭证
        //token具备一些条件就可以
        //1.唯一
        //2.需要加密
        //3.通过token能识别出哪个用户
        String tokenString =System.currentTimeMillis()+emp.getId()+"";//条件1: 生成唯一的字符串
        String token =DigestUtils.md5DigestAsHex(tokenString.getBytes(StandardCharsets.UTF_8));//条件2

        //条件3 : 通过该token 能识别出哪个用户
        redisTemplate.opsForValue().set(TokenConstant.EMPLOYEE_TOKEN_PREFIX+token, JSON.toJSONString(emp),30, TimeUnit.MINUTES);

        EmployeeVo emp1 = new EmployeeVo();
        BeanUtils.copyProperties(emp,emp1);
        emp1.setToken(token);

        return R.success(emp1);


//        //6. 登录成功,将员工id存入Session 并返回登入成功结果
//        request.getSession().setAttribute("employee",emp.getId());
//        return R.success(emp);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
       String token =request.getHeader("Authorization");
       redisTemplate.delete(TokenConstant.EMPLOYEE_TOKEN_PREFIX+token);
       log.info("执行了登出功能");
       return  R.success("登出成功");
    }

    /**
     *分页查询
     * @param page      第几页开始查询
     * @param pageSize  每页数据
     * @param name
     * @return
     */
    @GetMapping ("/page")
    public R<Page> selectPage( int page,int pageSize , String name){
        log.info("--------分页查询开始-------");
        Page page1 = employeeService.selectPage(page, pageSize, name);
        return R.success(page1) ;
    }
//    /**
//     *分页查询
//     * @param page      第几页开始查询
//     * @param pageSize  每页数据
//     * @param name
//     * @return
//     */
//    @GetMapping ("/page")
//    public R<Page> page(String name, Integer page, Integer pageSize) {
//        Page pageInfo = new Page(page, pageSize);
//        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper();
//        lqw.like(!StringUtils.isEmpty(name), Employee::getName, name);
//        lqw.orderByDesc(Employee::getUpdateTime);
//        employeeService.page(pageInfo, lqw);
//        return R.success(pageInfo);
//    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    // 有自动填充的字段需要加入几个工具类
    public R<String> Save(@RequestHeader("Authorization")String token , @RequestBody Employee employee){
        //1.判断新增的员工数据是否为空
        if(employee==null){
            return  R.error("添加失败");
        }
        //2.根据页面提交的用户名username 查询数据库
        LambdaQueryWrapper<Employee> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp1 =employeeService.getOne(queryWrapper);

        if(emp1!=null){
            return R.error(emp1.getUsername()+"已存在");
        }
        log.info("-----新增员工----");
        //根据token获取操作用户信息
//        String emp = redisTemplate.opsForValue().get(TokenConstant.EMPLOYEE_TOKEN_PREFIX + token);
//        if(!StringUtils.hasText(emp)){
//            return  R.error("未登录");
//        }
        //1.将前端页面获取的Employee对象复制给employeevo.
        //2.有关创建者和时间参数则由储存在redis里的用户决定参数.
        Employee employee2 = new Employee();

//        Employee employee1 = JSON.parseObject(emp, Employee.class);

//        employee.setCreateUser(TokenHolder.getCurrentId());
//        employee.setUpdateUser(TokenHolder.getCurrentId());
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        employee.setPassword("123456");

        BeanUtils.copyProperties(employee,employee2);
        employeeService.save(employee2);
        return  R.success("新增成功");
    }

    /**
     * 按照id 查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> selectById(@PathVariable String id){
       log.info("-----开始按照id查询员工信息------");
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getId, id);
        Employee employee = employeeService.getOne(queryWrapper);
        if(employee==null){
            return R.error("您输入的id不存在");
        }
        return R.success(employee);
    }

    /**
     * 修改员工状态---->启用员工
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> updateState( @RequestBody Employee employee){
        log.info("------修改员工权限状态-----");
        //获取待修改的员工信息
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getId,employee.getId());
        Employee emp = employeeService.getOne(queryWrapper);
        if(emp==null){
            log.info("输入的员工不存在");
            throw  new NoDataException();
        }
        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }
}
